package com.wz.utils.batch.service.impl;


import com.wz.utils.batch.exception.BatchWithRollBack;
import com.wz.utils.batch.exception.MsgException;
import com.wz.utils.batch.service.BatchWithService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.CountDownLatch;

@Service("batchWithService")
@Slf4j
public class BatchWithServiceImpl implements BatchWithService {

    @Override
    public Boolean childThreadRun(ProceedingJoinPoint joinPoint, Object[] args, CountDownLatch threadLatch, CountDownLatch mainLatch, BatchWithRollBack rollBack, BlockingDeque<Boolean> resultList) throws MsgException, SQLException {
        log.info("=====线程:"+Thread.currentThread().getName()+",开始执行====");
        long startTime = System.currentTimeMillis();
        Boolean result = false;
        try {
            joinPoint.proceed(args);
            result = true;
        } catch (Throwable throwable) {
            log.error("=====线程{}执行任务出现异常，等待主线程通知是否回滚,异常信息：{}",Thread.currentThread().getName(),throwable.getMessage());
            throwable.printStackTrace();
        }
        resultList.add(result);
        threadLatch.countDown();
        log.info("=====线程{},计算过程已经结束，等待主线程通知是否需要回滚====",Thread.currentThread().getName());
        long endTime = System.currentTimeMillis();
        long sec = (endTime - startTime)/1000;
        log.info("=====线程{},计算时间秒：{} ====",Thread.currentThread().getName(),sec);
        try {
            mainLatch.await();
            log.info("=====子线程{}再次启动",Thread.currentThread().getName());
        } catch (InterruptedException e) {
            throw new MsgException("批量处理，线程InterruptedException异常");
        }

        if (rollBack.getRollBack()) {
            log.info("=====线程{},线程回滚====",Thread.currentThread().getName());
            throw new MsgException("批量处理，线程回滚");
        }
        log.info("=====线程{},线程退出====",Thread.currentThread().getName());
        return result;
    }
}
